using MongoDB.Driver;
using newApi.Models;
using Microsoft.Extensions.Options;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.AspNetCore.Mvc;

namespace newApi.Services;
public class newsServices
{
    private readonly IMongoCollection<news> _newsCollection;

    public newsServices(IOptions<NewsLibDatabaseSettings> newsLibDatabaseSettings)
    {
        var mongoClient = new MongoClient(
                  newsLibDatabaseSettings.Value.ConnectionString);

        var mongoDatabase = mongoClient.GetDatabase(
            newsLibDatabaseSettings.Value.DatabaseName);

        _newsCollection = mongoDatabase.GetCollection<news>(
            newsLibDatabaseSettings.Value.newsCollectionName);




    }
    //   public Dictionary<string,object> GetNew(string channel,int num,int start){
    //         Dictionary<string,object> dictionaryNew = new Dictionary<string,object>();
    //         var findNews = _newsCollection.News.Where(s=>s.channel.Equals(channel)).Skip(start).Take(num);
    //         List<object> listNew = new List<object>();
    //         foreach(News news in findNews){
    //             var n = new {
    //                 title = news.title,
    //                 time = news.time,
    //                 src = news.src,
    //                 category = news.category,
    //                 pic = news.pic,
    //                 content = news.content,
    //                 url = news.url,
    //                 weburl = news.weburl,
    //             };
    //             listNew.Add(n);
    //         }
    //         Dictionary<string,object> dictionaryFindNew = new Dictionary<string,object>();
    //         dictionaryFindNew.Add("channel",channel);
    //         dictionaryFindNew.Add("num",num);
    //         dictionaryFindNew.Add("list",listNew);
            
    //         dictionaryNew.Add("status",0);
    //         dictionaryNew.Add("msg","ok");
    //         dictionaryNew.Add("result",dictionaryFindNew);
    //         return dictionaryNew;
    //     }

    public async Task<List<news>> GetAsync() =>
        await _newsCollection.Find(_ => true).ToListAsync();
    
    public async Task<news?> GetAsync(string id) =>
        await _newsCollection.Find(x => x.Id == id).FirstOrDefaultAsync();

    public async Task CreateAsync(news newNews) =>
        await _newsCollection.InsertOneAsync(newNews);

    public async Task UpdateAsync(string id, news updateNews) =>
        await _newsCollection.ReplaceOneAsync(x => x.Id == id, updateNews);

     public async Task RemoveAsync(string id) =>
        await _newsCollection.DeleteOneAsync(x => x.Id == id);


}